<template>
  <div class="singer-detail-container">
    <el-button
      class="back-btn"
      type="text"
      @click="goBack"
      style="margin-bottom: 16px"
    >
      返回
    </el-button>
    <!-- 歌手头部信息 -->
    <div class="singer-header">
      <img :src="artist.avatarUrl" alt="歌手头像" class="singer-avatar" />
      <div class="singer-info">
        <h1 class="singer-name">
          {{ artist.artistName }}
          <i
            v-if="artist.gender === 1"
            class="fas fa-mars gender-icon male-icon"
          ></i>
          <i
            v-else-if="artist.gender === 2"
            class="fas fa-venus gender-icon female-icon"
          ></i>
        </h1>
        <div class="singer-en-name">{{ artist.artistNameEn }}</div>
        <div class="artist-details">
          <div class="artist-detail-item" v-if="artist.country">
            <i class="fas fa-globe"></i> {{ artist.country }}
          </div>
          <div class="artist-detail-item" v-if="artist.birthDate">
            <i class="fas fa-birthday-cake"></i>
            {{ formatDate(artist.birthDate) }}
          </div>
          <div class="artist-detail-item" v-if="artist.genre">
            <i class="fas fa-music"></i> {{ artist.genre }}
          </div>
        </div>

        <div class="singer-intro-section" v-if="artist.introduction">
          <h3 class="intro-title">
            <i class="fas fa-info-circle"></i> 歌手介绍
          </h3>
          <div class="singer-description">{{ artist.introduction }}</div>
        </div>

        <div class="singer-stats">
          <div class="stat-item">
            <div class="stat-value">{{ statistics.songCount }}</div>
            <div class="stat-label">歌曲</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ statistics.albumCount }}</div>
            <div class="stat-label">专辑</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">
              {{ statistics.followerCount | formatNumber }}
            </div>
            <div class="stat-label">粉丝</div>
          </div>
        </div>

        <div class="action-buttons">
          <button class="action-button" @click="playArtistTopSongs">
            <i class="fas fa-play"></i> 播放热门歌曲
          </button>
          <button class="action-button" @click="followArtist">
            <i :class="isFollowing ? 'fas fa-check' : 'fas fa-plus'"></i>
            {{ isFollowing ? "已关注" : "关注" }}
          </button>
          <div class="share-menu">
            <button class="action-button">
              <i class="fas fa-share-alt"></i> 分享
            </button>
            <div class="share-options">
              <div class="share-option" @click="copyShareLink">
                <i class="fas fa-link"></i> 复制链接
              </div>
              <div class="share-option" @click="shareToWechat">
                <i class="fab fa-weixin"></i> 分享到微信
              </div>
              <div class="share-option" @click="shareToQQ">
                <i class="fab fa-qq"></i> 分享到QQ
              </div>
              <div class="share-option" @click="shareToWeibo">
                <i class="fab fa-weibo"></i> 分享到微博
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 标签页导航 -->
    <div class="tabs-container">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="全部歌曲" name="songs">
          <div class="tab-content">
            <div class="songs-container">
              <h2 class="section-title">
                <i class="fas fa-music"></i> 全部歌曲
              </h2>

              <div
                v-for="(song, index) in songs"
                :key="song.songId"
                class="song-item"
              >
                <div class="song-index">{{ index + 1 }}</div>
                <div class="song-info">
                  <div class="song-title">
                    <span @click="goToSongDetail(song)">{{
                      song.songName
                    }}</span>
                    <span v-if="song.isVip" class="vip-tag">VIP</span>
                  </div>
                  <div class="song-artist">
                    {{ artist.artistName }} · {{ getAlbumName(song.albumId) }}
                  </div>
                </div>
                <div class="song-duration">
                  {{ formatDuration(song.duration) }}
                </div>
                <div class="song-actions">
                  <el-button size="small" @click="playSong(song)" circle>
                    <el-icon><VideoPlay /></el-icon>
                  </el-button>
                  <el-button
                    size="small"
                    @click="showPlaylistDialog(song)"
                    circle
                  >
                    <el-icon><FolderAdd /></el-icon>
                  </el-button>
                  <el-button size="small" @click="handleCollect(song)" circle>
                    <el-icon
                      ><StarFilled
                        :style="song.isCollected ? '' : 'color: #bbb;'"
                    /></el-icon>
                  </el-button>
                  <el-button size="small" @click="shareSong(song)" circle>
                    <el-icon><Share /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="专辑" name="albums">
          <div class="tab-content">
            <div class="albums-container">
              <h2 class="section-title">
                <i class="fas fa-compact-disc"></i> 专辑
              </h2>

              <div class="album-grid">
                <div
                  v-for="album in albums"
                  :key="album.albumId"
                  class="album-card"
                  @click="viewAlbum(album)"
                >
                  <img
                    :src="album.coverUrl"
                    alt="专辑封面"
                    class="album-cover"
                  />
                  <div class="album-info">
                    <div class="album-title">{{ album.albumName }}</div>
                    <div class="album-release">
                      {{ album.releaseDate }} · {{ album.trackCount }}首
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import {
  FolderAdd,
  Share,
  StarFilled,
  VideoPlay,
} from "@element-plus/icons-vue";
import {
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElMessage,
  ElTabPane,
  ElTabs,
  ElTooltip,
} from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import api from "../services/api";

export default {
  name: "SingerDetail",
  components: {
    ElTabs,
    ElTabPane,
    ElDropdown,
    ElDropdownMenu,
    ElDropdownItem,
    ElTooltip,
    VideoPlay,
    FolderAdd,
    StarFilled,
    Share,
  },
  setup() {
    const route = useRouter().currentRoute.value;
    const artistId = route.params.id;
    const artist = reactive({
      artistId: artistId,
      artistName: "",
      artistNameEn: "",
      avatarUrl: "",
      coverUrl: "",
      gender: 0,
      country: "",
      birthDate: "",
      debutDate: "",
      genre: "",
      introduction: "",
      status: 1,
    });

    const statistics = reactive({
      albumCount: 0,
      songCount: 0,
      followerCount: 0,
      totalPlayCount: 0,
    });

    const songs = ref([]);
    const albums = ref([]);
    const userPlaylists = ref([]);
    const activeTab = ref("songs");
    const isFollowing = ref(false);
    const router = useRouter();

    // 参考 SongDetail 的 goBack 逻辑
    const goBack = () => {
      const from = route.query.from;
      if (from) {
        router.push(from);
      } else if (window.history.length > 1) {
        router.back();
      } else {
        router.push("/");
      }
    };

    const goToSongDetail = (song) => {
      if (song && song.songId) {
        router.push({
          name: "SongDetail",
          params: { id: song.songId },
          query: { from: router.currentRoute.value.fullPath },
        });
      }
    };

    const getAlbumName = (albumId) => {
      const album = albums.value.find((a) => a.albumId === albumId);
      return album ? album.albumName : "未知专辑";
    };

    const playArtistTopSongs = () => {
      ElMessage.success(`开始播放 ${artist.artistName} 的热门歌曲`);
    };

    const playSong = (song) => {
      ElMessage.success(`播放歌曲: ${song.songName}`);
    };

    const followArtist = () => {
      isFollowing.value = !isFollowing.value;
      ElMessage.success(
        isFollowing.value
          ? `已关注 ${artist.artistName}`
          : `已取消关注 ${artist.artistName}`
      );
    };

    const copyShareLink = () => {
      navigator.clipboard.writeText(
        `https://musicplatform.com/artist/${artist.artistId}`
      );
      ElMessage.success("歌手链接已复制到剪贴板");
    };

    const shareToWechat = () => ElMessage.info("分享到微信功能");
    const shareToQQ = () => ElMessage.info("分享到QQ功能");
    const shareToWeibo = () => ElMessage.info("分享到微博功能");

    const viewAlbum = (album) => {
      router.push({
        name: "AlbumDetails",
        params: { albumId: album.albumId },
      });
    };

    // 加载歌手详情
    const loadArtistData = async () => {
      try {
        const res = await api.artistApi.getArtistDetail(artistId);
        console.log("加载歌手详情成功:", res);
        let data = null;
        // 适配后端返回格式
        if (res && res.code === 200) {
          // 直接获取res.data作为数据，适配新的API响应格式
          data = res.data;
        }
        if (!data) {
          ElMessage.warning("未找到该歌手的信息");
          return;
        }
        Object.assign(artist, {
          artistId: data.artistId,
          artistName: data.artistName,
          artistNameEn: data.artistNameEn || "",
          avatarUrl: data.avatarUrl || "/images/default-avatar.jpg",
          coverUrl: data.coverUrl || "/images/default-cover.jpg",
          gender: data.gender,
          country: data.country,
          birthDate: data.birthDate,
          debutDate: data.debutDate,
          genre: data.genre,
          introduction: data.introduction || "这位歌手暂无介绍",
          status: data.status,
        });

        // 打印歌手信息，用于调试
        console.log("歌手介绍:", artist.introduction);

        // 统计信息直接从data赋值（适配后端新格式）
        Object.assign(statistics, {
          albumCount: data.albumCount ?? 0,
          songCount: data.songCount ?? 0,
          followerCount: data.followerCount ?? 0,
          totalPlayCount: data.totalPlayCount ?? 0,
        });
      } catch (e) {
        ElMessage.error("歌手信息加载失败");
        console.error("加载歌手详情失败:", e);
      }
    };

    // 加载歌手歌曲列表
    const loadSongsData = async () => {
      try {
        // 新接口：/songs/artist/{artistId}，返回data为数组
        const res = await api.artistApi.getArtistSongs(artistId);
        if (res && res.code === 200 && Array.isArray(res.data)) {
          songs.value = res.data;
        } else {
          songs.value = [];
        }
      } catch (e) {
        ElMessage.error("歌曲列表加载失败");
        console.error("歌曲列表加载失败:", e);
      }
    };

    // 加载歌手专辑列表
    const loadAlbumsData = async () => {
      try {
        const res = await api.artistApi.getArtistAlbums(artistId, {
          page: 1,
          pageSize: 20,
        });
        if (res && res.code === 200 && Array.isArray(res.data)) {
          albums.value = res.data;
        } else {
          albums.value = [];
        }
      } catch (e) {
        ElMessage.error("专辑列表加载失败");
        console.error("专辑列表加载失败:", e);
      }
    };

    onMounted(() => {
      loadArtistData();
      loadSongsData();
      loadAlbumsData();
    });

    const filters = {
      formatNumber(value) {
        if (value >= 100000000) return (value / 100000000).toFixed(1) + "亿";
        if (value >= 10000) return (value / 10000).toFixed(1) + "万";
        return value;
      },
      formatDuration(seconds) {
        const mins = Math.floor(seconds / 60);
        const secs = seconds % 60;
        return `${mins}:${secs.toString().padStart(2, "0")}`;
      },
    };

    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return "";
      const date = new Date(dateStr);
      return date.toLocaleDateString("zh-CN", {
        year: "numeric",
        month: "long",
        day: "numeric",
      });
    };

    return {
      artist,
      statistics,
      songs,
      albums,
      userPlaylists,
      activeTab,
      isFollowing,
      playArtistTopSongs,
      playSong,
      followArtist,
      copyShareLink,
      shareToWechat,
      shareToQQ,
      shareToWeibo,
      viewAlbum,
      getAlbumName,
      goBack,
      goToSongDetail,
      formatDate,
      ...filters,
    };
  },
};
</script>

<style scoped>
/* ...existing code... */

.artist-details {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin: 10px 0;
}

.artist-detail-item {
  background: rgba(255, 255, 255, 0.1);
  padding: 5px 10px;
  border-radius: 15px;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  gap: 6px;
}

.artist-detail-item i {
  color: rgba(255, 255, 255, 0.6);
}

.singer-intro-section {
  margin: 15px 0;
}

.intro-title {
  font-size: 1.2rem;
  margin-bottom: 8px;
  color: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  gap: 8px;
}

.back-btn {
  font-size: 16px;
  color: #6b46c1;
  margin-bottom: 16px;
}
:root {
  --primary-color: #a38faf;
  --secondary-color: #9c27b0;
  --bg-color: #121212;
  --card-bg: #1e1e1e;
  --text-primary: #ffffff;
  --text-secondary: #b3b3b3;
  --hover-color: #2a2a2a;
}

.singer-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.singer-header {
  display: flex;
  color: var(--primary-color);
  gap: 30px;
  margin-bottom: 40px;
  padding: 20px;
  background: linear-gradient(
    35deg,
    rgba(127, 116, 163, 0.7) 0%,
    var(--primary-color) 50%,
    var(--secondary-color) 100%
  );
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.singer-avatar {
  width: 240px;
  height: 240px;
  border-radius: 50%;
  border: 5px solid rgba(255, 255, 255, 0.1);
  object-fit: cover;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.4);
}

.singer-info {
  flex: 1;
  display: flex;
  color: balck;
  flex-direction: column;
  justify-content: center;
}

.singer-name {
  font-size: 2.8rem;
  font-weight: 800;
  margin-bottom: 10px;
  letter-spacing: -0.5px;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.singer-en-name {
  font-size: 1.4rem;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 15px;
}

.singer-description {
  font-size: 1rem;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.6;
  margin: 15px 0;
  padding: 10px;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  max-height: 120px;
  overflow-y: auto;
  white-space: pre-line;
}

.singer-stats {
  display: flex;
  gap: 30px;
  margin: 20px 0;
}

.stat-item {
  text-align: center;
  padding: 10px 20px;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 8px;
  min-width: 120px;
}

.stat-value {
  font-size: 1.8rem;
  font-weight: 700;
  color: var(--primary-color);
}

.stat-label {
  font-size: 0.9rem;
  color: var(--text-secondary);
  text-transform: uppercase;
  letter-spacing: 1px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.section-title {
  font-size: 1.8rem;
  margin: 30px 0 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid var(--primary-color);
  display: flex;
  align-items: center;
  gap: 10px;
}

.section-title i {
  color: var(--primary-color);
}

.songs-container,
.albums-container {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

.song-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border-radius: 8px;
  transition: background-color 0.3s;
  margin-bottom: 8px;
}

.song-item:hover {
  background-color: var(--hover-color);
}

.song-index {
  width: 40px;
  text-align: center;
  color: var(--text-secondary);
  font-size: 1.1rem;
}

.song-info {
  flex: 1;
}

.song-title {
  font-size: 1.1rem;
  font-weight: 500;
  margin-bottom: 4px;
}

.song-artist {
  font-size: 0.9rem;
  color: var(--text-secondary);
}

.song-duration {
  width: 80px;
  text-align: right;
  color: var(--text-secondary);
}

.song-actions {
  display: flex;
  gap: 15px;
  margin-left: 20px;
}

.action-icon {
  font-size: 1.1rem;
  color: var(--text-secondary);
  cursor: pointer;
  transition: color 0.3s;
}

.action-icon:hover {
  color: var(--primary-color);
}

.album-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 20px;
}

.album-card {
  background: #c3b7c7;
  border-radius: 10px;
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
  cursor: pointer;
}

.album-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3);
}

.album-cover {
  width: 100%;
  aspect-ratio: 1/1;
  object-fit: cover;
}

.album-info {
  padding: 15px;
}

.album-title {
  font-size: 1.1rem;
  font-weight: 500;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.album-release {
  font-size: 0.85rem;
  color: var(--text-secondary);
}

.tabs-container {
  margin-top: 30px;
}

.tab-content {
  margin-top: 20px;
}

.play-button {
  background-color: var(--primary-color);
  border: none;
  color: white;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 4px 15px rgba(233, 30, 99, 0.4);
}

.play-button:hover {
  transform: scale(1.05);
  background-color: #d81b60;
}

.action-button {
  background: rgba(255, 255, 255, 0.1);
  border: none;
  color: white;
  border-radius: 20px;
  padding: 8px 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-button:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

.share-menu {
  position: relative;
}

.share-options {
  position: absolute;
  top: 100%;
  right: 0;
  background: var(--card-bg);
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  z-index: 10;
  min-width: 200px;
  display: none;
}

.share-menu:hover .share-options {
  display: block;
}

.share-option {
  padding: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-radius: 6px;
  cursor: pointer;
}

.share-option:hover {
  background: var(--hover-color);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.vip-tag {
  background: linear-gradient(45deg, #ff9800, #ff5722);
  color: white;
  font-size: 0.75rem;
  padding: 2px 8px;
  border-radius: 4px;
  margin-left: 8px;
  display: inline-block;
}

.gender-icon {
  font-size: 1.2rem;
  margin-left: 10px;
}

.male-icon {
  color: #64b5f6;
}

.female-icon {
  color: #f48fb1;
}

@media (max-width: 768px) {
  .singer-header {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .singer-stats {
    justify-content: center;
  }

  .action-buttons {
    justify-content: center;
  }

  .album-grid {
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
  }
}
</style>
